package com.hundsun.s3.mrs.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hundsun.s3.mrs.core.talker.Talker;
import com.hundsun.s3.mrs.core.talker.TalkerManager;
import com.hundsun.s3.mrs.core.task.DefTask;
import com.hundsun.s3.mrs.core.task.Task;
import com.hundsun.s3.mrs.core.task.TaskManager;
import com.hundsun.s3.mrs.pub.dto.TaskDto;
import com.hundsun.s3.mrs.pub.dto.UserDto;
import com.hundsun.s3.mrs.pub.utils.BizSecurity;
import com.hundsun.s3.mrs.service.ContentService;

@Controller
public class ContentAction {
	
	@Autowired
	private ContentService contentService;
	
	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory.getLogger(ContentAction.class);
	
	@RequestMapping("/index.htm")
	public void index(ModelMap mm) {
		mm.put("key1", BizSecurity.key1);
		mm.put("key2", BizSecurity.key2);
		mm.put("key3", BizSecurity.key3);
		mm.put("wsPort", contentService.getWsPort());
	}
	
	@RequestMapping("/manager/allInfo.json")
	@ResponseBody
	public Map<String, Object> allInfo() {
		Map<String, Object> res = new HashMap<>();
		List<UserDto> list = new ArrayList<>();
		Map<String, Talker> talkerMapper = TalkerManager.getTalkerMapper();
		Iterator<Talker> iterator = talkerMapper.values().iterator();
		while(iterator.hasNext()) {
			Talker talker = iterator.next();
			String id = talker.getId();
			UserDto userDto = new UserDto();
			userDto.setId(id);
			userDto.setName(talker.getName());
			userDto.setLoginTime(talker.getLoginTime());
			userDto.setLogoutTime(talker.getLogoutTime());
			userDto.setGroups(talker.getGroups());
			userDto.setOnline(talker.isOnline());
			list.add(userDto);
		}
		res.put("rows", list);
		res.put("total", list.size());
		return res;
	}
	
	@RequestMapping("/manager/taskQueue.json")
	@ResponseBody
	public Map<String, Object> taskQueue() {
		Map<String, Object> res = new HashMap<>();
		List<TaskDto> taskList = new ArrayList<>();
		TaskDto taskDto;
		List<Task> list = TaskManager.getAll();
		if(list==null) {
			return res;
		} 
		for(Task task : list) {
			taskDto = new TaskDto(task.getTaskId(), ((DefTask)task).getMessage());
			taskList.add(taskDto);
		}
		res.put("rows", taskList);
		res.put("total", taskList.size());
		return res;
	}
	
	
}
